/*****************************************************************
    Copyright (c) 2009 Julian M Bucknall

    Permission is hereby granted, free of charge, to any person
    obtaining a copy of this software and associated documentation
    files (the "Software"), to deal in the Software without
    restriction, including without limitation the rights to use,
    copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the
    Software is furnished to do so, subject to the following
    conditions:

    The above copyright notice and this permission notice shall be
    included in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
    OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
    HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
    WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
    OTHER DEALINGS IN THE SOFTWARE.
******************************************************************/
using System;
using System.Text;

namespace JmbCalendar {

  public delegate string DayLinkGenerator(object sender, DayLinkEventArgs e);
  public delegate string MonthLinkGenerator(object sender, MonthLinkEventArgs e);

  public class HtmlCalendar {
    private string prevMonthFormat;
    private string nextMonthFormat;
    private int year;
    private int month;
    private DayLinkGenerator generateDayLink;
    private MonthLinkGenerator generateMonthLink;
    private char[] DayLetters;
    private string[] DayNumbers = {"0",  "1",  "2",  "3",  "4",  "5",  "6",  "7",  "8",  "9", 
		                                   "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", 
		                                   "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", 
		                                   "30", "31"};

    public HtmlCalendar(int year, int month) {
      this.year = year;
      this.month = month;
      GetDayLetters();
    }

    public static string GetMonthName(int m) {
      if (1 <= m && m <= 12)
        return System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.MonthNames[m - 1];
      return string.Format("Invalid month number: {0}", m);
    }

    public static string GetAbbrMonthName(int m) {
      if (1 <= m && m <= 12)
        return System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.AbbreviatedMonthNames[m - 1];
      return string.Format("Invalid month number: {0}", m);
    }

    public string Render() {
      StringBuilder sb = new StringBuilder();
      sb.AppendLine("<table id='jmbCalendar'>");
      AddCalendarCaption(sb);
      AddCalendarHeader(sb);
      AddCalendarFooter(sb);
      AddCalendarBody(sb);
      sb.AppendLine("</table>");
      return sb.ToString();
    }

    private string GetMonthLink() {
      string monthLink = OnGenerateMonthLink(year, month, true, false);
      if (string.IsNullOrEmpty(monthLink))
        monthLink = string.Format("{0} {1}", GetMonthName(month), year);
      return monthLink;
    }

    private void AddCalendarCaption(StringBuilder sb) {
      sb.Append("<caption>");
      sb.Append(GetMonthLink());
      sb.AppendLine("</caption>");
    }

    private void AddCalendarHeader(StringBuilder sb) {
      sb.Append("<thead>");
      sb.Append("<tr>");
      foreach (char d in DayLetters)
        sb.AppendFormat("<th>{0}</th>", d);
      sb.Append("</tr>");
      sb.AppendLine("</thead>");
    }

    private string GetAbbrMonthLink(int year, int month, bool forPrevMonth) {
      string monthLink = OnGenerateMonthLink(year, month, false, forPrevMonth);
      if (string.IsNullOrEmpty(monthLink))
        if (forPrevMonth)
          monthLink = string.Format(PrevMonthFormat, GetAbbrMonthName(month));
        else
          monthLink = string.Format(NextMonthFormat, GetAbbrMonthName(month));
      return monthLink;
    }

    private void AddCalendarFooter(StringBuilder sb) {
      int prevMonth = month - 1;
      int prevYear = year;
      if (prevMonth == 0) {
        prevMonth = 12;
        prevYear = year - 1;
      }

      int nextMonth = month + 1;
      int nextYear = year;
      if (nextMonth == 13) {
        nextMonth = 1;
        nextYear = year + 1;
      }
      DateTime firstOfNextMonth = new DateTime(nextYear, nextMonth, 1);
      bool displayNextLink = (firstOfNextMonth <= DateTime.Now);

      sb.Append("<tfoot>");
      sb.Append("<tr>");
      sb.AppendFormat("<td colspan='3'>{0}</td>", GetAbbrMonthLink(prevYear, prevMonth, true));
      sb.Append("<td colspan='1'>&nbsp;</td>");
      if (displayNextLink)
        sb.AppendFormat("<td colspan='3'>{0}</td>", GetAbbrMonthLink(nextYear, nextMonth, false));
      else
        sb.Append("<td colspan='3'>&nbsp;</td>");
      sb.Append("</tr>");
      sb.AppendLine("</tfoot>");
    }

    private static int AddCalendarRow(StringBuilder sb, string[] days, int cdn) {
      sb.Append("<tr>");
      for (int i = 0; i < 7; i++) {
        sb.AppendFormat("<td>{0}</td>", days[cdn++]);
      }
      sb.AppendLine("</tr>");
      return cdn;
    }

    private void AddCalendarBody(StringBuilder sb) {
      sb.AppendLine("<tbody>");

      // a month calendar has a maximum of 6 rows, 42 cells
      string[] days = new string[42];

      int firstEntry = (int)new DateTime(year, month, 1).DayOfWeek;
      int lastDay = DateTime.DaysInMonth(year, month);
      int day = 1;
      for (int i = firstEntry; i < firstEntry + lastDay; i++) {
        string dayLink = OnGenerateDayLink(day);
        if (string.IsNullOrEmpty(dayLink))
          dayLink = DayNumbers[day];
        days[i] = dayLink;
        day++;
      }

      // there will always be at least 4 rows
      int cdn = 0;
      for (int i = 0; i < 4; i++) {
        cdn = AddCalendarRow(sb, days, cdn);
      }
      // rows 5 and 6 may or may not be there
      if (!string.IsNullOrEmpty(days[cdn])) {
        cdn = AddCalendarRow(sb, days, cdn);
        if (!string.IsNullOrEmpty(days[cdn])) {
          cdn = AddCalendarRow(sb, days, cdn);
        }
      }

      sb.AppendLine("</tbody>");
    }

    private void GetDayLetters() {
      string[] dayNames = System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.DayNames;

      DayLetters = new char[7];
      int i = (int)System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.FirstDayOfWeek;

      foreach (string name in dayNames) {
        DayLetters[i] = name[0];
        i++;
        if (i >= 7) i = 0;
      }
    }

    protected virtual string OnGenerateDayLink(int day) {
      DayLinkGenerator handler = GenerateDayLink;
      if (handler == null)
        return string.Empty;
      DayLinkEventArgs args = new DayLinkEventArgs(year, month, day);
      return handler(this, args);
    }

    protected virtual string OnGenerateMonthLink(int year, int month, bool fullName, bool forPrevMonth) {
      MonthLinkGenerator handler = GenerateMonthLink;
      if (handler == null)
        return String.Empty;
      MonthLinkEventArgs args = new MonthLinkEventArgs(year, month, fullName, forPrevMonth);
      return handler(this, args);
    }

    public DayLinkGenerator GenerateDayLink {
      get { return generateDayLink; }
      set { generateDayLink = value; }
    }
    public MonthLinkGenerator GenerateMonthLink {
      get { return generateMonthLink; }
      set { generateMonthLink = value; }
    }
    public int Year {
      get { return year; }
    }
    public int Month {
      get { return month; }
    }
    public string PrevMonthFormat {
      get { return prevMonthFormat; }
      set { prevMonthFormat = value; }
    }
    public string NextMonthFormat {
      get { return nextMonthFormat; }
      set { nextMonthFormat = value; }
    }

  }
}
